/*
 * Copyright 2011 www.pretty-tools.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


#include "stdafx.h"
#include "ArgumentTransfer.h"


// CArgumentTransfer
CArgumentTransfer::CArgumentTransfer()
    : m_dwCookie(0)
{
    ATLTRACE( _T("CArgumentTransfer::CArgumentTransfer()\n") );
}

CArgumentTransfer::~CArgumentTransfer()
{
    ATLTRACE( _T("CArgumentTransfer::~CArgumentTransfer()\n") );
}


STDMETHODIMP CArgumentTransfer::Attach(IDispatch* pBrowser, VARIANT parameters)
{
    ATLTRACE( _T("CArgumentTransfer::Attach(...)\n") );

    if (m_dwCookie)
        return E_UNEXPECTED;

    if ((VT_ARRAY|VT_VARIANT) != parameters.vt)
        return E_INVALIDARG;

    WEBBrowser browser(pBrowser);
    if (!browser)
        return E_INVALIDARG;

	if (FAILED(AtlAdvise(browser, GetUnknown(), DIID_DWebBrowserEvents2, &m_dwCookie)))
		return E_FAIL;

    m_browser2 = browser;
    m_parameters = parameters.parray;

    return S_OK;
}

STDMETHODIMP CArgumentTransfer::Detach(void)
{
    ATLTRACE( _T("CArgumentTransfer::Detach()\n") );

    if (!m_browser2)
        return S_FALSE;

	AtlUnadvise(m_browser2, DIID_DWebBrowserEvents2, m_dwCookie), m_dwCookie = 0;
	m_browser2.Release();
    m_parameters.Destroy();

    return S_OK;
}

STDMETHODIMP CArgumentTransfer::DocumentComplete(IDispatch* pDisp, VARIANT* URL)
{
#ifdef _DEBUG
	if (URL && (URL->vt & VT_BSTR) && URL->bstrVal)
		ATLTRACE( _T("CArgumentTransfer::DocumentComplete %s\n"), CString(URL->bstrVal) );
	else
		ATLTRACE( _T("CArgumentTransfer::DocumentComplete - Cannot read location\n") );
#endif

    WEBBrowser browser(pDisp);
    if (!browser)
        return S_OK;

	try
	{
        JS::Method addArgument = m_browser2.document.parentWindow.method[L"addArgument"];
        if (!addArgument)
            return S_OK;

        for (int i = 0, count = m_parameters.GetCount(); i < count; ++i)
        {
            addArgument(m_parameters[i]);
        }
	}
	catch (...)
	{
		ATLTRACE( _T("EXEPTION on call javascript 'addArgument'\n") );
	}

    return S_OK;
}